const router = require('koa-router')()

router.prefix('/login')

// 生成token
const jwt = require('jsonwebtoken');
const koaJwt = require('koa-jwt');

// 引入解密模块
const JSEncrypt = require('node-jsencrypt');



// 生成雪花ID的方法
const createSnow = function (ctx) {
  let snowFlake = ctx.snowFlake;
  let snowId = snowFlake.createSnow(1);
  return snowId;
}



router.get("/getPublicKey", async (ctx, next) => {
  let snowFlake = ctx.snowFlake;
  let snowId = snowFlake.createSnow(1);
  console.log(snowId, "这个是雪花ID");
  console.log(ctx.config);
  ctx.body = { publicKey: ctx.state.publicKey };
})

router.post('/submit', async(ctx, next) => {
    let data = ctx.request.body;
    
    // 创建decrypt对象，对密码进行解密
    const decrypt = new JSEncrypt();
    decrypt.setPrivateKey(ctx.state.privateKey);
    console.log(data);
    let sql = 'select * from user'
    let res = await ctx.db.EXCUTE(sql, []);
    let obj = res.find(i => {return i.user_name == data.username && decrypt.decrypt(i.user_password) == decrypt.decrypt(data.password)});
    if(obj) {
      const user = { username: data.username, user_id: obj.user_id, user_auth: obj.user_auth};
      // 从全局变量中拿出secretKey
      // 生成 token
      const token = jwt.sign(user, ctx.config.secretKey, { expiresIn: '3h' });
      const refreshToken = jwt.sign({auth: true}, ctx.config.secretKey, { expiresIn: '7d' });
      let user_info = {};
      // 通过身份来查询其对应的信息
      console.log(obj.user_auth, "身份");
      if(obj.user_auth === "student_per"){
        console.log("此时身份是学生");
        ctx.body = {code: 500, msg: "学生不能登录后台管理系统"}
      } else {
        user_info = {...user_info, user_auth: obj.user_auth}
        console.log(JSON.stringify(user_info));
        user_info = ctx.Aes.aesEncrypt(ctx, JSON.stringify(user_info))
        ctx.body = {code: 200, msg: "成功登陆", token, refreshToken, user_info: user_info}
      }
    } else {
      ctx.body = {code: 500, type: "error", message: "用户名或密码错误"}
    }
  // ctx.cookies.set('token', token, { httpOnly: true, domain: "localhost", path: '/', overwrite: true });
})

router.post("/userInfo", async(ctx, next) => {
  console.log(ctx.request.body.user_info);
  let data = ctx.request.body;
  let user_info = JSON.parse(ctx.Aes.aesDecrypt(ctx, data.user_info));
  console.log(user_info)
  ctx.body = {user_info};
})



module.exports = router